
#include "unixhead.h"
#include <iostream>

using namespace std;
using std::cout;
using std::endl;


class HttpServer
{
public:
    HttpServer(const string & ip, unsigned short port)
    : _ip(ip)
    , _port(port)
    {}

    void start()
    {
        _listenfd = socket(AF_INET, SOCK_STREAM, 0);
        if(_listenfd < 0) {
            perror("socket");
            return;
        }

        int on = 1;
        int ret = setsockopt(_listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
        if(ret < 0) {
            perror("setsockopt");
            return;
        }

        struct sockaddr_in serveraddr;
        serveraddr.sin_family = AF_INET;
        serveraddr.sin_port = htons(_port);
        serveraddr.sin_addr.s_addr = inet_addr(_ip.c_str());

        ret = bind(_listenfd, (struct sockaddr*)&serveraddr, sizeof(serveraddr));
        if(ret < 0) {
            perror("bind");
            return;
        }

        ret = listen(_listenfd, 10);
        if(ret < 0) {
            perror("listen");
            return;
        }
    }

    void recvAndShow()
    {
        while(1) {
            printf("wait clients\n");
            int peerfd = accept(_listenfd, nullptr, nullptr);
            char buff[1024] = {0};
            int ret = recv(peerfd, buff, sizeof(buff), 0);

            printf("recv %d bytes, buff: \n%s\n", ret, buff);

            string resp = response();
            ret = send(peerfd, resp.c_str(), resp.size(), 0);

            close(peerfd);
        }
    }

    string response()
    {
        string firstline = "HTTP/1.1 200 OK\r\n";
        string headers = "Content-Type: text/html\r\n";
        headers += "Server: wangdao server\r\n";
        string emptyline = "\r\n";
        string body = "<html><body>hello,http</body></html>";

        return firstline + headers + emptyline + body;
    }


    ~HttpServer()
    {
        close(_listenfd);
    }


private:
    const string _ip;
    unsigned short _port;
    int _listenfd;
};

void test0()
{
    HttpServer httpserver("0.0.0.0", 1280);
    httpserver.start();
    httpserver.recvAndShow();
}


int main()
{
    test0();
    return 0;
}

